﻿using FaceWebServer.DB.Device;
using FaceWebServer.Interface;
using FaceWebServer.Model;
using FaceWebServer.Utility;
using FC8280TServer.Controllers.DeviceAPI;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using DoNetDrive.Common.Extensions;

namespace FC8280TServer.Controllers
{
    [Route("[controller]")]
    [ApiController]
    [ServiceFilter(typeof(FaceAPILogResourceFilter))]
    public class FaceAPIController : ControllerBase
    {

        private readonly ILogger<FaceAPIController> _logger;

        private IRecordService _RecordDB;
        private IFaceDriveService _DriveDB;
        private ITimeGroupService _TimeGroupDB;
        private IDeviceRemoteService _RemoteDB;

        public FaceAPIController(ILogger<FaceAPIController> logger, IMyMemoryCache mycache, 
            IFaceDriveService faceDrive, 
            IRecordService record, ITimeGroupService timegroupdb, IDeviceRemoteService remoteDB)
        {
            _logger = logger;
            _RecordDB = record;
            _DriveDB = faceDrive;
            _TimeGroupDB = timegroupdb;
            _RemoteDB = remoteDB;
        }

        #region 打卡记录
        /// <summary>
        /// 设备主动往云端实时上传打卡记录
        /// </summary>
        /// <param name="record"></param>
        /// <returns></returns>
        [Route("note/insertNoteFace")]
        [HttpPost]
        public async Task<JsonResult> UploadRecord([FromForm] string recordJson, [FromForm] IFormCollection files)
        {
            DriveRecord record = JsonConvert.DeserializeObject<DriveRecord>(recordJson);

            _logger.LogInformation($"设备上传记录 note/insertNoteFace {record.deviceId} {record.noteTime} \r\n {recordJson}");
            if (record.pic_len > 0 && files.Files.Count == 1)
            {

                string sPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "RecordImage", record.deviceId);
                if (!Directory.Exists(sPath))
                {
                    Directory.CreateDirectory(sPath);
                }
                string sFileName = $"{record.noteTime.ToString("yyyy-MM-dd_HH_mm_ss")}_{Guid.NewGuid().ToString("N")}.jpg";
                string sFile = Path.Combine(sPath, sFileName);
                var uploadFile = files.Files[0];
                if (uploadFile.Length > 0)
                {
                    record.pic_len = (int)uploadFile.Length;

                    using (var stream = new FileStream(sFile, FileMode.Create))
                    {
                        await uploadFile.CopyToAsync(stream);
                    }
                    record.imgURL = $"/RecordImage/{record.deviceId}/{sFileName}";
                }
            }
            else
            {
                record.pic_len = 0;
            }
            _RecordDB.AddRecord(record);

            return new JsonResult(new FaceAPIResult());
        }
        #endregion


        #region 保活包
        /// <summary>
        /// 心跳保活包
        /// </summary>
        [Route("device/updateStateDevice")]
        [HttpPost]
        public IActionResult DeviceKeepalive([FromBody] DeviceKeepaliveRequest par)
        {
            var result = new DeviceKeepaliveResult();

            _logger.LogInformation($" 设备心跳包 device/updateStateDevice SN:{par.DeviceId}");

            if (string.IsNullOrWhiteSpace(par.DeviceId))
            {
                result.SyncParameter = 1;
            }
            else
            {
                #region 检查参数是否需要同步
                FaceDeviceDetail oDevice;
                oDevice = _DriveDB.GetDetail(par.DeviceId);

                #endregion




                if (oDevice != null)
                {
                    #region 检查权限是否需要同步
                    (result.AddPeople, result.DeletePeople, result.Remote) = _DriveDB.GetTaskDetail(par.DeviceId);
                    #endregion

                    oDevice = _DriveDB.Find<FaceDeviceDetail>(oDevice.ID);
                    oDevice.LastKeepaliveTime = DateTime.Now;
                    oDevice.OnlineTime = DateTime.Now;
                    if (oDevice.UploadStatus == 0)
                    {
                        result.SyncParameter = 1;
                    }
                    _DriveDB.UpdateCache(oDevice);
                    _DriveDB.Update(oDevice);
                }

            }

            return new JsonResult(result);
        }


        #endregion

        #region 人员操作
        /// <summary>
        ///  添加人员 设备主动触发云端导入雇员授权信息
        /// </summary>
        [Route("devicePass/selectPassInfo")]
        [HttpPost]
        public IActionResult ReadPeople(ReadPeopleRequestRequest par)
        {
            _logger.LogInformation($" 设备拉取人事信息 DeviceKeepalive SN:{par.DeviceId}");
            ReadPeopleResult rst = new();
            rst.PassInfo = new List<DevicePeopleModel>();
            DevicePeopleModel p = new DevicePeopleModel()
            {
                EmployeeID = 1,
                EmployeeName = "赖金杰",
                EmployeeJob = "开发",
                EmployeePassword = "123456",
                EmployeeRoot = 0,
                TimegroupID = 1,
                EmployeePhotoWay = "path",
                EmployeePhoto = "/people/1.jpg",
                EmployeeIc = 123,
                EmployeePhone = "13711304610",
                EmployeeShold = 0,
                EmployeeIdentity = "",
                EmployeeAddress = ""
            };
            p.DevicePassBean.SetAccessDeadline(DateTime.Now.AddMinutes(10));
            rst.PassInfo.Add(p);
            return new JsonResult(rst);
        }



        /// <summary>
        /// 添加人员反馈  拉取人员导入人脸机后的结果反馈
        /// </summary>
        [Route("devicePass/setPassResult")]
        [HttpPost]
        public IActionResult ReadPeopleResult([FromBody] DeviceReadPeopleResultRequest par)
        {
            return new JsonResult(new FaceAPIResult());
        }



        /// <summary>
        /// 删除人员   拉取待删除的人员
        /// </summary>
        [Route("devicePass/selectDeleteInfo")]
        [HttpPost]
        public IActionResult DeletePeople([FromBody] ReadPeopleRequestRequest par)
        {
            var rst = new DeletePeopleResult();
            rst.DeleteInfo = new List<PeopleResultDetail>();
            return new JsonResult(rst);
        }

        /// <summary>
        /// 删除人员反馈   设备从服务器拉取的待删除的人员操作后的结果反馈
        /// </summary>
        [Route("devicePass/setDeleteResult")]
        [HttpPost]
        public IActionResult ReadDeletePeople([FromBody] DeviceDeletePeopleResultRequest par)
        {
            return new JsonResult(new FaceAPIResult());
        }
        #endregion


        #region 远程操作指令
        /// <summary>
        /// 远程操作 设备请求远程操作任务
        /// </summary>
        /// <param name="par"></param>
        /// <returns></returns>
        [Route("device/selectRestart")]
        [HttpPost]
        public IActionResult DeviceRemote([FromBody] DeviceRemoteRequest par)
        {
            var device = _DriveDB.GetDetail(par.DeviceId);
            if(device == null)
            {
                return new JsonResult(new FaceAPIResult() { success = 1, msg = "请先上传参数" });
            }

            var Remotes = _RemoteDB.GetRemoteTaskByDeviceID(device.ID);

            var result = new DeviceRemoteResult();

            foreach (var item in Remotes)
            {
                switch (item.TaskType)
                {
                    case 1://1，远程开门
                        result.Opendoor = 1;
                        break;
                    case 2://2、远程重启
                        result.Restart = 1;
                        break;
                    case 3://3、恢复出厂设置
                        result.Recover = 1;
                        break;
                    case 4://4、关闭报警
                        result.Closealarm = 1;
                        break;
                    default:
                        break;
                }
                _RemoteDB.UpdateTaskRunStatusComplete(device.ID, item.TaskType);
            }

            return new JsonResult(result);
        }
        #endregion


        #region 属性配置
        /// <summary>
        ///  上传参数 设备将机器现有配置上传服务器
        /// </summary>
        /// <param name="par"></param>
        /// <returns></returns>
        [Route("parameter/inertParameter")]
        [HttpPost]
        public IActionResult UploadWorkParameter([FromBody] FaceDeviceDetail par)
        {
            if (string.IsNullOrWhiteSpace(par.DeviceID))
            {
                return new JsonResult(new FaceAPIResult());//没有SN不处理
            }
            par.DeviceName = par.DeviceID;

            

            _DriveDB.Add(par);


            return new JsonResult(new FaceAPIResult());
        }

        /// <summary>
        ///  拉取参数 设备请求同步参数，将服务器存储内容发送到设备
        /// </summary>
        /// <param name="par"></param>
        /// <returns></returns>
        [Route("parameter/selectParameterInfo")]
        [HttpPost]
        public IActionResult GetWorkParameter([FromBody] BaseDeviceRequest par)
        {
            GetWorkParameterResult detail;
            if (string.IsNullOrWhiteSpace(par.DeviceId))
            {
                var defValue = _DriveDB.GetDefaultValue();

                //从数据库拉取默认值发过去
                detail = defValue.ToJSON().FromJson<GetWorkParameterResult>();
               
            }
            else
            {
                //去数据库中查询
                var device = _DriveDB.GetDetail(par.DeviceId);
                if (device != null)
                {
                    detail = device.ToJSON().FromJson<GetWorkParameterResult>();
                }
                else
                {
                    return new JsonResult(new FaceAPIResult() { success = 1, msg = "请先上传参数" });
                }
            }

            detail.ParameterSystemTime = TimestampUtility.ToUnixTimestampBySeconds(DateTime.Now);
            detail.ParameterSerialNum = detail.DeviceID;
            detail.Timegroups = _TimeGroupDB.GetAll();
            return new JsonResult(detail);
        }


    }
    #endregion


}
